package com.decade.config.shiro;

import com.decade.domain.User;
import com.decade.service.UserService;
import com.decade.vo.ActiverUser;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;

/**
 * @author: decade
 * @Description: 自定义realm去匹配用户名和密码
 * @date: 2021/1/23 20:22
 */
public class UserRealm extends AuthorizingRealm {
    @Autowired
    @Lazy
    private UserService userService;

    /**
     * 通过反射获取类名
     * */
    @Override
    public String getName() {
        return this.getClass().getSimpleName();
    }

    /**
     * 做认证--就是登录
     * */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户登录名
        String phone = token.getPrincipal().toString();
        //根据电话查询用户是否存在
        User user = userService.queryUserByPhone(phone);
        if (null!=user){//说明用户存在，但是密码可能不正确
            //组装存放到redis里面的对象
            ActiverUser activerUser = new ActiverUser();
            activerUser.setUser(user);
            //匹配密码
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                    activerUser,user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName()
            );
            return info;
        }
        return null;//代表用户不存在
    }

    /**
     * 授权 -- 登录成功之后判断用户是否有某个菜单或按钮的权限
     * */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //身份得到的就是上一个方法的返回值的值 第一个参数activerUser
        ActiverUser activerUser =(ActiverUser) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        return info;
    }
}
